package com.one.group.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.one.group.enums.ErrorCode;
import com.one.group.model.dto.PositionAddDto;
import com.one.group.model.dto.PositionListDto;
import com.one.group.model.dto.PositionQueryDto;
import com.one.group.model.entity.Admin;
import com.one.group.model.entity.Position;
import com.one.group.model.vo.PositionVo;
import com.one.group.result.Result;
import com.one.group.service.AdminService;
import com.one.group.service.PositionService;
import com.one.group.utils.ResultUtil;
import com.one.group.utils.ThrowUtil;
import com.one.group.utils.WebUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * @Author wanbo
 * @Date 2025/10/11 15:48
 */
@Slf4j
@RestController
@RequestMapping("/position")
@Tag(name = "机构和岗位管理")
public class PositionController {

    @Autowired
    private PositionService positionService;

    @PostMapping("/tree")
    @Operation(summary = "获取岗位树")
    public Result getPositionTree(@RequestBody PositionQueryDto positionQueryDto){
        List<PositionVo> positionList = positionService.selectPositionTree(positionQueryDto);
        return ResultUtil.success(positionList);
    }

    @PostMapping("/treeByQuery")
    @Operation(summary = "根据条件获取岗位树")
    public Result getPositionTreeByQuery(@RequestBody PositionQueryDto positionQueryDto){
        if (ObjectUtil.isEmpty(positionQueryDto)) {
            log.error("岗位列表参数为空：positionQueryDto：{}", positionQueryDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "岗位列表参数为空");
        }
        // 查询机构和部门
        List<PositionVo> positionList = positionService.selectPositionTreeByQuery(positionQueryDto);
        return ResultUtil.success(positionList);
    }

    @PostMapping("/listPosition")
    @Operation(summary = "获取部门列表")
    public Result getPositionList(@RequestBody PositionListDto positionListDto){
        if (ObjectUtil.isEmpty(positionListDto)){
            log.error("岗位列表参数为空：positionQueryDto：{}", positionListDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "岗位列表参数为空");
        }
        if (positionListDto.getCellId()==null || positionListDto.getCellId()<=0){
            log.error("岗位列表参数错误：cellId：{}", positionListDto.getCellId());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "部门列表参数错误：cellId");
        }
        if (positionListDto.getType()==null || positionListDto.getType()<0 || positionListDto.getType()>2){
            log.error("岗位列表参数错误：type：{}", positionListDto.getType());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "type参数错误：type");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StpUtil.getLoginId().equals("1")){
            queryWrapper.eq(Position::getTenantId, Convert.toLong(StpUtil.getExtra("tenant_id")));
        }

        queryWrapper.eq(Position::getCellId,positionListDto.getCellId());
        queryWrapper.eq(Position::getType,positionListDto.getType());

        List<Position> positionList = positionService.list(queryWrapper);
        return ResultUtil.success(positionList);
    }

    @PostMapping("/add")
    @Operation(summary = "添加机构")
    public Result addOrgination(@RequestBody PositionAddDto positionAddDto) {
        if (ObjectUtil.isEmpty(positionAddDto)){
            log.error("岗位添加参数为空：positionAddDto：{}", positionAddDto);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "岗位添加参数为空");
        }

        if (positionAddDto.getType()==null || positionAddDto.getType()<0){
            log.error("岗位添加参数错误：type：{}", positionAddDto.getType());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "岗位添加参数错误：type");
        }

        if(StrUtil.isEmpty(positionAddDto.getPosNumber())){
            log.error("岗位添加参数错误：posNumber：{}", positionAddDto.getPosNumber());
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "岗位添加参数错误：posNumber");
        }

        Position position = new Position();
        BeanUtil.copyProperties(positionAddDto, position);
        position.setTenantId(Convert.toLong(StpUtil.getExtra("tenant_id")));

        boolean result = positionService.save(position);

        return result?ResultUtil.success(position):ResultUtil.error(ErrorCode.OPERATION_ERROR);
    }

    @GetMapping("/getPositionById")
    @Operation(summary = "根据id获取")
    public Result getPositionById(@RequestParam Long id) {
        Position position = positionService.getPositionById(id);
        return ResultUtil.success(position);
    }

    @PostMapping("/update")
    @Operation(summary = "修改岗位接口")
    public Result update(@RequestBody Position position) {
        ThrowUtil.throwIf(ObjectUtil.isEmpty(position), ErrorCode.PARAMS_ERROR, "岗位修改参数为空");
        boolean result = positionService.updateById(position);
        return result?ResultUtil.success(position):ResultUtil.error(ErrorCode.OPERATION_ERROR);
    }

    @GetMapping("/delete")
    @Operation(summary = "删除岗位接口")
    public Result delete(@RequestParam Long id) {
        if (id<=0){
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "id不能为空");
        }

        // 查询该id是机构、部门还是岗位
        Position position = positionService.getById(id);
        if (ObjectUtil.isEmpty(position)){
            log.error("该{}岗位不存在",id);
            ThrowUtil.throwIf(true, ErrorCode.PARAMS_ERROR, "id不存在");
        }
        boolean result = false;
        if (position.getType()==2){
            // 是岗位  删除
            result = positionService.removeById(id);
        } else {
            // 是机构、部门 删除部门及其子部门的岗位
            result = positionService.removePositionAndChild(id);
        }

        return result?ResultUtil.success(id):ResultUtil.error(ErrorCode.OPERATION_ERROR);
    }

    @PostMapping("/batchDelete")
    @Operation(summary = "批量删除岗位接口")
    public Result batchDelete(@RequestBody List<Long> id) {
        if (id == null || id.isEmpty()) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR, "请选择要删除的岗位");
        }

        try {
            // 执行批量删除
            boolean result = positionService.removeByIds(id);
            return result ? ResultUtil.success() : ResultUtil.error(ErrorCode.OPERATION_ERROR, "删除失败");
        } catch (Exception e) {
            log.error("批量删除岗位失败，ids: {}", id, e);
            return ResultUtil.error(ErrorCode.OPERATION_ERROR, "删除失败：" + e.getMessage());
        }
    }

}
